#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import os
import sys

def merge_jemalloc_lines(input_file, output_file=None, in_place=False):
    """
    将包含"jemalloc heap"的行与上一行合并
    
    参数:
        input_file: 输入文件路径
        output_file: 输出文件路径（如果为None且in_place=False，则打印到控制台）
        in_place: 是否原地修改文件
    """
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            lines = f.readlines()
    except UnicodeDecodeError:
        try:
            with open(input_file, 'r', encoding='latin-1') as f:
                lines = f.readlines()
        except Exception as e:
            print(f"读取文件失败: {e}")
            return False
    
    # 处理行合并
    merged_lines = []
    i = 0
    while i < len(lines):
        current_line = lines[i].rstrip('\n\r')
        
        # 检查下一行是否包含"jemalloc heap"
        if i + 1 < len(lines) and "jemalloc heap" in lines[i + 1]:
            next_line = lines[i + 1].rstrip('\n\r')
            # 合并当前行和下一行
            merged_line = current_line + " " + next_line
            merged_lines.append(merged_line)
            i += 2  # 跳过下一行，因为已经合并了
        else:
            merged_lines.append(current_line)
            i += 1
    
    # 输出结果
    if in_place:
        # 原地修改文件
        with open(input_file, 'w', encoding='utf-8') as f:
            for line in merged_lines:
                f.write(line + '\n')
        print(f"文件已原地修改: {input_file}")
        return True
    elif output_file:
        # 写入到输出文件
        with open(output_file, 'w', encoding='utf-8') as f:
            for line in merged_lines:
                f.write(line + '\n')
        print(f"结果已保存到: {output_file}")
        return True
    else:
        # 打印到控制台
        for line in merged_lines:
            print(line)
        return True

def create_sample_file():
    """创建示例文件用于测试"""
    sample_content = """应用启动日志
内存统计: {'TimeSatamp': 1756796001.230954, 'GL': 65512, 'Graph': 127596, 'ark ts heap': 176468, 'native heap': 284574, 'AnonPage other': 365126, 'FilePage other': 57091, 'Total': 12033
55, jemalloc heap': 274040}
用户操作日志
内存统计: {"TimeSatamp": 1756796002.451234, "GL": 65890, "Graph": 128123, "ark ts heap": 177231, "native heap": 285672, "AnonPage other": 366543, "FilePage other": 57234, "Total": 1207890}
jemalloc heap': 275195}
性能监控
内存统计: {'TimeSatamp': 1756796003.789012, 'GL': 66234, 'Graph': 128567, 'ark ts heap': 178456, 'native heap': 286789, 'AnonPage other': 367890, 'FilePage other': 57456, 'Total': 1212345}
jemalloc heap': 276123}
错误处理
内存统计: {"TimeSatamp": 1756796004.123456, "GL": 66543, "Graph": 129012, "ark ts heap": 179234, "native heap": 287456, "AnonPage other": 368765, "FilePage other": 57678, "Total": 1216789}
jemalloc heap': 277456}"""
    
    with open('sample_jemalloc.txt', 'w', encoding='utf-8') as f:
        f.write(sample_content)
    
    print("示例文件已创建: sample_jemalloc.txt")
    return 'sample_jemalloc.txt'

def main():
    parser = argparse.ArgumentParser(description='合并包含"jemalloc heap"的行与上一行')
    parser.add_argument('input_file', nargs='?', help='输入文件路径')
    parser.add_argument('-o', '--output', help='输出文件路径')
    parser.add_argument('-i', '--in-place', action='store_true', help='原地修改文件')
    parser.add_argument('--sample', action='store_true', help='创建示例文件并处理')
    parser.add_argument('--verbose', action='store_true', help='显示详细信息')
    
    args = parser.parse_args()
    
    if args.sample:
        input_file = create_sample_file()
        print("\n处理示例文件:")
        merge_jemalloc_lines(input_file, output_file="output_sample.txt")
        
        # # 显示处理前后的对比
        # print("\n处理前:")
        # with open(input_file, 'r', encoding='utf-8') as f:
        #     print(f.read())
        
        # print("\n处理后:")
        # with open("output_sample.txt", 'r', encoding='utf-8') as f:
        #     print(f.read())
        
        return
    
    if not args.input_file:
        print("请提供输入文件路径或使用 --sample 参数")
        parser.print_help()
        return
    
    if not os.path.exists(args.input_file):
        print(f"文件不存在: {args.input_file}")
        return
    
    if args.in_place and args.output:
        print("错误: 不能同时使用 --in-place 和 --output 参数")
        return
    
    if args.verbose:
        print(f"处理文件: {args.input_file}")
        if args.in_place:
            print("模式: 原地修改")
        elif args.output:
            print(f"输出到: {args.output}")
        else:
            print("模式: 输出到控制台")
    
    success = merge_jemalloc_lines(
        input_file=args.input_file,
        output_file=args.output,
        in_place=args.in_place
    )
    
    if success and args.verbose:
        print("处理完成")

if __name__ == "__main__":
    main()